package com.tongtong.controller.email.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tongtong.common.WebConstants;
import com.tongtong.controller.email.entity.TtEmailConfig;
import com.tongtong.controller.email.service.TtEmailConfigService;
import com.tt.utils.EncryptionUtils;
import com.tt.utils.R;
import com.tongtong.controller.email.utils.SendEmailUtils;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 邮箱控制类
 * @author zl
 */
@RestController
@RequestMapping("/email")
public class EmailController {
    @Autowired
    private TtEmailConfigService ttEmailConfigService;

    @GetMapping("/getEmailConfig")
    public R getEmailConfig(@RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize,
                            @RequestParam(value = "name",required = false) String name){
        PageHelper.startPage(pageNum,pageSize);
        QueryWrapper queryWrapper = new QueryWrapper();
        if(StrUtil.isNotEmpty(name)){
            queryWrapper.like("email",name);
        }
        queryWrapper.eq("status",0);
        List<TtEmailConfig> list = ttEmailConfigService.list(queryWrapper);
        PageInfo pageInfo = new PageInfo(list);
        return R.ok().put("data",pageInfo);
    }
    @SneakyThrows
    @PostMapping("/saveEmailConfig")
    public R saveEmailConfig(@RequestBody TtEmailConfig ttEmailConfig){
        SendEmailUtils sendEmailUtils = new SendEmailUtils();
        boolean b = sendEmailUtils.validateEmailPassword(ttEmailConfig);
        if(!b) {
            throw new RuntimeException("密码输入错误");
        }
        ttEmailConfig.setPassword(EncryptionUtils.encryptWithAES(ttEmailConfig.getPassword(), WebConstants.PASSWORDKEY));
        ttEmailConfigService.save(ttEmailConfig);
        return R.ok();
    }
    @PostMapping("/deleteEmailConfig/{id}")
    public R deleteEmailConfig(@PathVariable("id") Integer id){
        TtEmailConfig ttEmailConfig = new TtEmailConfig();
        ttEmailConfig.setId(id);
        ttEmailConfig.setStatus(1);
        ttEmailConfigService.updateById(ttEmailConfig);
        return R.ok();
    }
    @PostMapping("/updateEmailSign")
    public R updateEmailSign(@RequestBody TtEmailConfig config){
        ttEmailConfigService.updateById(config);
        return R.ok();
    }


}
